package com.datagateway.controller;

import com.datagateway.component.DataBuffer;
import com.datagateway.component.GroovyScriptEngine;
import com.datagateway.component.HiveWriter;
import com.datagateway.component.RetryQueue;
import com.datagateway.component.AlertManager;
import com.datagateway.component.SystemMonitor;
import com.datagateway.component.PartitionManager;
import com.datagateway.component.DataQualityChecker;
import com.datagateway.component.GracefulShutdownManager;
import com.datagateway.component.PerformanceOptimizer;
import com.datagateway.component.ConfigHotReloadManager;
import com.datagateway.component.DataCompressionManager;
import com.datagateway.component.DataSerializationManager;
import com.datagateway.component.MemoryManager;
import com.datagateway.component.MemoryLeakDetector;
import com.datagateway.component.MultiDataSourceManager;
import com.datagateway.component.MultiDataSourceRouter;
import com.datagateway.component.DataLineageTracker;
import com.datagateway.component.DataLineageVisualizer;
import com.datagateway.component.DataBackupManager;
import com.datagateway.component.DataRecoveryManager;
import com.datagateway.component.DataEncryptionManager;
import com.datagateway.component.DataTransmissionEncryptionManager;
import com.datagateway.component.LoadBalancerManager;
import com.datagateway.component.ServiceDiscoveryManager;
import com.datagateway.component.DataStatisticsManager;
import com.datagateway.component.ReportGenerator;
import com.datagateway.component.ScriptVersionManager;
import com.datagateway.component.ScriptABTestManager;
import com.datagateway.component.RateLimiterManager;
import com.datagateway.component.CircuitBreakerManager;
import com.datagateway.component.DegradationManager;
import com.datagateway.component.DataFormatConverter;
import com.datagateway.component.DataValidationEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

import java.util.HashMap;
import java.util.Map;

/**
 * 健康检查和监控控制器
 * 提供系统状态监控和统计信息
 * 
 * @author Data Gateway Team
 * @version 1.0.0
 */
@RestController
@RequestMapping("/api/health")
public class HealthController {

    @Autowired
    private DataBuffer dataBuffer;

    @Autowired
    private GroovyScriptEngine groovyScriptEngine;

    @Autowired
    private HiveWriter hiveWriter;

    @Autowired
    private RetryQueue retryQueue;

    @Autowired
    private AlertManager alertManager;

    @Autowired
    private SystemMonitor systemMonitor;

    @Autowired
    private PartitionManager partitionManager;

    @Autowired
    private DataQualityChecker dataQualityChecker;

    @Autowired
    private GracefulShutdownManager gracefulShutdownManager;

    @Autowired
    private PerformanceOptimizer performanceOptimizer;

    @Autowired
    private ConfigHotReloadManager configHotReloadManager;

    @Autowired
    private DataCompressionManager compressionManager;

    @Autowired
    private DataSerializationManager serializationManager;

    @Autowired
    private MemoryManager memoryManager;

    @Autowired
    private MemoryLeakDetector memoryLeakDetector;

    @Autowired
    private MultiDataSourceManager multiDataSourceManager;

    @Autowired
    private MultiDataSourceRouter multiDataSourceRouter;

    @Autowired
    private DataLineageTracker dataLineageTracker;

    @Autowired
    private DataLineageVisualizer dataLineageVisualizer;

    @Autowired
    private DataBackupManager dataBackupManager;

    @Autowired
    private DataRecoveryManager dataRecoveryManager;

    @Autowired
    private DataEncryptionManager dataEncryptionManager;

    @Autowired
    private DataTransmissionEncryptionManager transmissionEncryptionManager;

    @Autowired
    private LoadBalancerManager loadBalancerManager;

    @Autowired
    private ServiceDiscoveryManager serviceDiscoveryManager;

    @Autowired
    private DataStatisticsManager dataStatisticsManager;

    @Autowired
    private ReportGenerator reportGenerator;

    @Autowired
    private ScriptVersionManager scriptVersionManager;

    @Autowired
    private ScriptABTestManager scriptABTestManager;

    @Autowired
    private RateLimiterManager rateLimiterManager;

    @Autowired
    private CircuitBreakerManager circuitBreakerManager;

    @Autowired
    private DegradationManager degradationManager;

    @Autowired
    private DataFormatConverter dataFormatConverter;

    @Autowired
    private DataValidationEngine dataValidationEngine;

    /**
     * 获取系统健康状态
     * 
     * @return 系统健康状态信息
     */
    @GetMapping("/status")
    public Map<String, Object> getHealthStatus() {
        Map<String, Object> status = new HashMap<>();
        
        try {
            // 获取数据缓冲区状态
            DataBuffer.BufferStatus bufferStatus = dataBuffer.getStatus();
            status.put("dataBuffer", bufferStatus);
            
            // 获取Groovy脚本引擎状态
            Map<String, Object> scriptStatus = groovyScriptEngine.getCacheStatus();
            status.put("groovyScriptEngine", scriptStatus);
            
            // 获取Hive写入统计
            HiveWriter.WriteStatistics writeStats = hiveWriter.getWriteStatistics();
            status.put("hiveWriter", writeStats);
            
            // 获取重试队列统计
            RetryQueue.RetryStatistics retryStats = retryQueue.getRetryStatistics();
            status.put("retryQueue", retryStats);
            
            // 获取告警统计
            AlertManager.AlertStatistics alertStats = alertManager.getAlertStatistics();
            status.put("alertManager", alertStats);
            
            // 获取系统性能统计
            SystemMonitor.SystemPerformanceStatistics perfStats = systemMonitor.getSystemPerformanceStatistics();
            status.put("systemPerformance", perfStats);
            
            // 获取内存使用情况
            SystemMonitor.MemoryUsageInfo memoryInfo = systemMonitor.getMemoryUsageInfo();
            status.put("memoryUsage", memoryInfo);
            
            // 获取分区统计信息
            PartitionManager.PartitionStatistics partitionStats = partitionManager.getPartitionStatistics();
            status.put("partitionManager", partitionStats);
            
            // 获取数据质量统计
            DataQualityChecker.QualityStatistics qualityStats = dataQualityChecker.getQualityStatistics();
            status.put("dataQuality", qualityStats);
            
            // 获取优雅关闭状态
            GracefulShutdownManager.ShutdownStatus shutdownStatus = gracefulShutdownManager.getShutdownStatus();
            status.put("shutdownStatus", shutdownStatus);
            
            // 获取性能指标
            PerformanceOptimizer.PerformanceMetrics performanceMetrics = performanceOptimizer.getCurrentPerformanceMetrics();
            status.put("performanceMetrics", performanceMetrics);
            
            // 获取性能统计
            PerformanceOptimizer.PerformanceStatistics performanceStats = performanceOptimizer.getPerformanceStatistics();
            status.put("performanceStatistics", performanceStats);
            
            // 获取配置热更新状态
            ConfigHotReloadManager.ConfigHotReloadStatistics configStats = configHotReloadManager.getStatistics();
            status.put("configHotReload", configStats);
            
            // 获取数据压缩统计
            DataCompressionManager.CompressionStatistics compressionStats = compressionManager.getStatistics();
            status.put("compression", compressionStats);
            
            // 获取数据序列化统计
            DataSerializationManager.SerializationStatistics serializationStats = serializationManager.getStatistics();
            status.put("serialization", serializationStats);
            
            // 获取内存管理统计
            MemoryManager.MemoryStatistics memoryStats = memoryManager.getStatistics();
            status.put("memory", memoryStats);
            
            // 获取内存泄漏检测统计
            MemoryLeakDetector.MemoryLeakDetectionStatistics leakStats = memoryLeakDetector.getDetectionStatistics();
            status.put("memoryLeakDetection", leakStats);
            
            // 获取多数据源统计
            MultiDataSourceManager.MultiDataSourceStatistics multiDataSourceStats = multiDataSourceManager.getStatistics();
            status.put("multiDataSource", multiDataSourceStats);
            
            // 获取路由统计
            MultiDataSourceRouter.RouteStatistics routeStats = multiDataSourceRouter.getRouteStatistics();
            status.put("routing", routeStats);
            
            // 获取数据血缘统计
            DataLineageTracker.DataLineageStatistics lineageStats = dataLineageTracker.getStatistics();
            status.put("dataLineage", lineageStats);
            
            // 获取数据血缘可视化统计
            DataLineageVisualizer.VisualizationStatistics visualizationStats = dataLineageVisualizer.getStatistics();
            status.put("dataLineageVisualization", visualizationStats);
            
            // 获取数据备份统计
            DataBackupManager.BackupStatistics backupStats = dataBackupManager.getStatistics();
            status.put("dataBackup", backupStats);
            
            // 获取数据恢复统计
            DataRecoveryManager.RecoveryStatistics recoveryStats = dataRecoveryManager.getStatistics();
            status.put("dataRecovery", recoveryStats);
            
            // 获取数据加密统计
            DataEncryptionManager.EncryptionStatistics encryptionStats = dataEncryptionManager.getStatistics();
            status.put("dataEncryption", encryptionStats);
            
               // 获取传输加密统计
               DataTransmissionEncryptionManager.TransmissionEncryptionStatistics transmissionStats = 
                   transmissionEncryptionManager.getStatistics();
               status.put("transmissionEncryption", transmissionStats);
               
               // 获取负载均衡统计
               LoadBalancerManager.LoadBalancingStatistics loadBalancerStats = loadBalancerManager.getStatistics();
               status.put("loadBalancer", loadBalancerStats);
               
               // 获取服务发现统计
               ServiceDiscoveryManager.ServiceDiscoveryStatistics serviceDiscoveryStats = serviceDiscoveryManager.getStatistics();
               status.put("serviceDiscovery", serviceDiscoveryStats);
               
               // 获取数据统计信息
               DataStatisticsManager.SystemStatistics dataStats = dataStatisticsManager.getSystemStatistics();
               status.put("dataStatistics", dataStats);
               
               // 获取报表生成器状态
               List<ReportGenerator.ReportFile> reports = reportGenerator.getReportList();
               status.put("reportGenerator", Map.of(
                   "reportCount", reports.size(),
                   "reports", reports
               ));
               
               // 获取脚本版本管理统计
               ScriptVersionManager.ScriptVersionStatistics scriptVersionStats = scriptVersionManager.getStatistics();
               status.put("scriptVersionManager", scriptVersionStats);
               
               // 获取A/B测试统计
               ScriptABTestManager.ABTestStatistics abTestStats = scriptABTestManager.getStatistics();
               status.put("scriptABTestManager", abTestStats);
               
               // 获取限流统计
               RateLimiterManager.RateLimiterStatistics rateLimiterStats = rateLimiterManager.getStatistics();
               status.put("rateLimiterManager", rateLimiterStats);
               
               // 获取熔断器统计
               CircuitBreakerManager.CircuitBreakerStatistics circuitBreakerStats = circuitBreakerManager.getStatistics();
               status.put("circuitBreakerManager", circuitBreakerStats);
               
               // 获取降级统计
               DegradationManager.DegradationStatistics degradationStats = degradationManager.getStatistics();
               status.put("degradationManager", degradationStats);
               
               // 获取数据格式转换统计
               DataFormatConverter.ConversionStatistics conversionStats = dataFormatConverter.getStatistics();
               status.put("dataFormatConverter", conversionStats);
               
               // 获取数据校验统计
               DataValidationEngine.ValidationStatistics validationStats = dataValidationEngine.getStatistics();
               status.put("dataValidationEngine", validationStats);
               
               // 系统状态
               status.put("status", "UP");
               status.put("timestamp", System.currentTimeMillis());
            
        } catch (Exception e) {
            status.put("status", "DOWN");
            status.put("error", e.getMessage());
            status.put("timestamp", System.currentTimeMillis());
        }
        
        return status;
    }

    /**
     * 获取数据缓冲区状态
     * 
     * @return 数据缓冲区状态
     */
    @GetMapping("/buffer")
    public DataBuffer.BufferStatus getBufferStatus() {
        return dataBuffer.getStatus();
    }

    /**
     * 获取Groovy脚本引擎状态
     * 
     * @return 脚本引擎状态
     */
    @GetMapping("/groovy")
    public Map<String, Object> getGroovyStatus() {
        return groovyScriptEngine.getCacheStatus();
    }

    /**
     * 获取Hive写入统计
     * 
     * @return 写入统计信息
     */
    @GetMapping("/hive")
    public HiveWriter.WriteStatistics getHiveStatistics() {
        return hiveWriter.getWriteStatistics();
    }

    /**
     * 强制刷新数据缓冲区
     * 
     * @return 操作结果
     */
    @GetMapping("/buffer/flush")
    public Map<String, Object> flushBuffer() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            dataBuffer.flush();
            result.put("success", true);
            result.put("message", "数据缓冲区刷新成功");
            result.put("timestamp", System.currentTimeMillis());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "数据缓冲区刷新失败: " + e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
        }
        
        return result;
    }

    /**
     * 清除Groovy脚本缓存
     * 
     * @return 操作结果
     */
    @GetMapping("/groovy/clear-cache")
    public Map<String, Object> clearGroovyCache() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            groovyScriptEngine.clearCache();
            result.put("success", true);
            result.put("message", "Groovy脚本缓存清除成功");
            result.put("timestamp", System.currentTimeMillis());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "Groovy脚本缓存清除失败: " + e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
        }
        
        return result;
    }

    /**
     * 获取重试队列统计
     * 
     * @return 重试队列统计信息
     */
    @GetMapping("/retry")
    public RetryQueue.RetryStatistics getRetryStatistics() {
        return retryQueue.getRetryStatistics();
    }

    /**
     * 获取死信队列数据
     * 
     * @return 死信队列数据
     */
    @GetMapping("/retry/dead-letter")
    public Map<String, Object> getDeadLetterData() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            var deadLetterData = retryQueue.getDeadLetterData();
            result.put("success", true);
            result.put("data", deadLetterData);
            result.put("count", deadLetterData.size());
            result.put("timestamp", System.currentTimeMillis());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取死信队列数据失败: " + e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
        }
        
        return result;
    }

    /**
     * 清空死信队列
     * 
     * @return 操作结果
     */
    @GetMapping("/retry/dead-letter/clear")
    public Map<String, Object> clearDeadLetterQueue() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            retryQueue.clearDeadLetterQueue();
            result.put("success", true);
            result.put("message", "死信队列清空成功");
            result.put("timestamp", System.currentTimeMillis());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "死信队列清空失败: " + e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
        }
        
        return result;
    }

    /**
     * 获取告警统计信息
     * 
     * @return 告警统计信息
     */
    @GetMapping("/alerts")
    public AlertManager.AlertStatistics getAlertStatistics() {
        return alertManager.getAlertStatistics();
    }

    /**
     * 获取系统性能统计
     * 
     * @return 系统性能统计信息
     */
    @GetMapping("/performance")
    public SystemMonitor.SystemPerformanceStatistics getSystemPerformanceStatistics() {
        return systemMonitor.getSystemPerformanceStatistics();
    }

    /**
     * 获取内存使用情况
     * 
     * @return 内存使用情况
     */
    @GetMapping("/memory")
    public SystemMonitor.MemoryUsageInfo getMemoryUsageInfo() {
        return systemMonitor.getMemoryUsageInfo();
    }

    /**
     * 发送测试告警
     * 
     * @return 操作结果
     */
    @GetMapping("/alerts/test")
    public Map<String, Object> sendTestAlert() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            alertManager.sendAlert(
                AlertManager.AlertLevel.INFO,
                AlertManager.AlertType.SYSTEM_ERROR,
                "测试告警",
                "这是一个测试告警消息",
                "用于验证告警系统是否正常工作"
            );
            
            result.put("success", true);
            result.put("message", "测试告警发送成功");
            result.put("timestamp", System.currentTimeMillis());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "测试告警发送失败: " + e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
        }
        
        return result;
    }

    /**
     * 获取分区统计信息
     * 
     * @return 分区统计信息
     */
    @GetMapping("/partitions")
    public PartitionManager.PartitionStatistics getPartitionStatistics() {
        return partitionManager.getPartitionStatistics();
    }

    /**
     * 获取活跃分区列表
     * 
     * @return 活跃分区列表
     */
    @GetMapping("/partitions/active")
    public List<PartitionManager.PartitionInfo> getActivePartitions() {
        return partitionManager.getActivePartitions();
    }

    /**
     * 清理过期分区
     * 
     * @param retentionDays 保留天数
     * @return 操作结果
     */
    @GetMapping("/partitions/cleanup")
    public Map<String, Object> cleanupExpiredPartitions(int retentionDays) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            partitionManager.cleanupExpiredPartitions(retentionDays);
            result.put("success", true);
            result.put("message", "过期分区清理成功，保留天数: " + retentionDays);
            result.put("timestamp", System.currentTimeMillis());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "过期分区清理失败: " + e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
        }
        
        return result;
    }

    /**
     * 获取数据质量统计
     * 
     * @return 数据质量统计信息
     */
    @GetMapping("/quality")
    public DataQualityChecker.QualityStatistics getDataQualityStatistics() {
        return dataQualityChecker.getQualityStatistics();
    }

    /**
     * 初始化默认质量规则
     * 
     * @return 操作结果
     */
    @GetMapping("/quality/init-rules")
    public Map<String, Object> initializeQualityRules() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            dataQualityChecker.initializeDefaultRules();
            result.put("success", true);
            result.put("message", "默认质量规则初始化成功");
            result.put("timestamp", System.currentTimeMillis());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "默认质量规则初始化失败: " + e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
        }
        
        return result;
    }

    /**
     * 获取优雅关闭状态
     * 
     * @return 优雅关闭状态信息
     */
    @GetMapping("/shutdown/status")
    public GracefulShutdownManager.ShutdownStatus getShutdownStatus() {
        return gracefulShutdownManager.getShutdownStatus();
    }

    /**
     * 触发优雅关闭
     * 
     * @return 操作结果
     */
    @GetMapping("/shutdown/trigger")
    public Map<String, Object> triggerGracefulShutdown() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 注意：这里只是演示API，实际生产环境中应该通过系统信号触发关闭
            result.put("success", true);
            result.put("message", "优雅关闭已触发，请使用系统信号（SIGTERM）进行实际关闭");
            result.put("timestamp", System.currentTimeMillis());
            result.put("note", "生产环境请使用: kill -TERM <pid> 或 docker stop <container>");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "触发优雅关闭失败: " + e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
        }
        
        return result;
    }
}
